﻿using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Common;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System;
using System.Collections.Generic;
using System.Data;

namespace lwzlz.Application.System
{
    public class UserService
    {
        private readonly IRepository<User> _repository;
        private LoginUser _user { get { return UserAuthentication.GetCurrentUser(); } }

        public UserService()
        {
            _repository = new Repository<User>();
        }

        #region 获取实体
        public User Get(int id)
        {
            return _repository.Get(id);
        }
        /// <summary>
        /// 获取输出对象
        /// </summary>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public TDto Get<TDto>(int id) where TDto : class, new()
        {
            var entity = Get(id);
            return Mapper.Map<TDto>(entity);
        }
        #endregion

        #region 添加
        public int? Add(UserInput model)
        {
            var entity = Mapper.Map<User>(model);
            var dbtran = _repository.BeginTransaction();
            int? id = default(int?);
            try
            {
                // 查重
                int count = CheckUnique(model, dbtran);
                entity.CreatorUserId = _user.UserID;
                entity.CreationTime = DateTime.Now;
                entity.UserPWD = new Symmetric().Encrypto(entity.UserPWD);
                id = _repository.Insert(entity, dbtran);
                dbtran.Commit();
            }
            catch (Exception)
            {
                dbtran.Rollback();
                throw;
            }
            finally
            {
                dbtran.Dispose();
                int ID = _repository.QueryFirstOrDefault("select ID from Sys_User where UserName=@UserName", new { @UserName = model.UserName }).Id;
            }
            return id;
        }
        #endregion

        #region 修改
        public int Eidt(UserInput model)
        {
            int number = 0;
            var dbtran = _repository.BeginTransaction();
            try
            {

                var entity = _repository.Get(model.Id, dbtran);
                string pwd = entity.UserPWD;
                if (entity.UserName != model.UserName)
                {
                    // 查重
                    int count = CheckUnique(model, dbtran);
                }
                Mapper.Map(model, entity);
                entity.LastModificationTime = DateTime.Now;
                entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.UserPWD = pwd;
                number = _repository.Update(entity, dbtran);
                dbtran.Commit();
            }
            catch (Exception ex)
            {
                dbtran.Rollback();
                throw new Exception(ex.Message);
            }
            finally
            {
                dbtran.Dispose();
            }
            return number;
        }
        #endregion

        #region 检测用户名唯一性
        protected int CheckUnique(UserInput model, IDbTransaction dbtran)
        {
            // 查询相同用户名
            var count = _repository.RecordCount("WHERE UserName=@UserName and IsDeleted=0", new { @UserName = model.UserName }, dbtran);
            if (count > 0)
            {
                throw new DBConcurrencyException("用户名已存在");
            }

            return count;
        }
        #endregion

        #region 生成随机密码
        public string CreateRandomPwd()
        {
            string pwd = string.Empty;
            string s = "0123456789";
            Random random = new Random();

            for (int i = 0; i < 6; i++)
            {
                pwd += s[random.Next(s.Length)];
            }

            return pwd;
        }
        #endregion

        #region 获得分页数据
        public IEnumerable<dynamic> GetDynamicPaged(int pageNumber, int rowsPerPage, string orderby, string sql, object param = null)
        {
            return _repository.GetDynamicPaged(pageNumber, rowsPerPage, orderby, sql, param);
        }
        public int RecordQueryCount(string sql, object param)
        {
            return _repository.RecordQueryCount(sql, param);
        }
        #endregion

        #region 更新
        public int UpDataSave(User model)
        {
            return _repository.Update(model);
        }
        #endregion

        #region 批量删除
        public void DeleteList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(','))
                {
                    User model = _repository.Get(Id, dbtran);
                    model.IsDeleted = true;
                    model.DeletionTime = DateTime.Now;
                    model.DeleterUserId = UserAuthentication.GetCurrentUser().UserID;
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }
        #endregion

        #region 解除锁定
        public void LockList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(','))
                {
                    User model = _repository.Get(Id, dbtran);
                    if (model.IsLock == true)
                    {
                        model.IsLock = false;
                    }
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }
        #endregion

        #region 修改密码
        public int EditPWD(UserChangePwdInput model)
        {
            //数据库参数
            Dictionary<string, object> dic = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(model.NewPWD2))
            {
                var newpwd = new Symmetric().Encrypto(model.NewPWD2);
                dic.Add("@NewPWD2", newpwd);
            }
            dic.Add("@ID", UserAuthentication.GetCurrentUser().UserID);
            //string sql = string.Format("update User set UserPWD='{0}',ModifyDate=getdate() where ID='{1}'", new Symmetric().Encrypto(model.NewPWD2).ToString(), UserAuthentication.GetCurrentUser().UserID);
            string sql = "update [Sys_User] set UserPWD=@NewPWD2 where ID=@ID";

            return _repository.Execute(sql, dic);

        }
        #endregion

        /// <summary>
        /// 获取数据
        /// </summary>
        public IEnumerable<dynamic> GetListBysql(string sql, object param)
        {
            return _repository.QueryDynamic(sql, param);
        }
    }
}
